<?php

namespace common\components;

use yii\filters\auth\AuthMethod;
use Firebase\JWT\JWT;
use Exception;
use Yii;

class JwtAuthor extends AuthMethod
{
    /**
     * {@inheritdoc}
     */
    public function authenticate($user, $request, $response)
    {
        $authHeader = (string)$request->getHeaders()->get('Authorization', "");
        if ($authHeader) {
            try {
                $token = JWT::decode($authHeader, Yii::$app->params['jwt_key'], ['HS256']);
            } catch (Exception $e) {
                return NULL;
            }
            if ($token === NULL) return NULL;
            return $user->loginByAccessToken($token, get_class($this));
        }
        return NULL;
    }

    public function challenge($response)
    {
        $response->getHeaders()->set(
            'fusen-authenticate',
            " error=\"invalid_token\", error_description=\"The access token invalid or expired\""
        );
    }
}
